#include "mycamera.h"
#include "ui_mycamera.h"
#include "toast.h"
#include <QDateTime>
#include <opencv.hpp>
#include <maincsv.h>
#include <QMessageBox>

MyCamera::MyCamera(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MyCamera)
{
    ui->setupUi(this);
    ui->label->hide();
}

MyCamera::~MyCamera()
{
    // // 关闭相机，释放相机
    if(m_camera){
        stopCamera();
        m_camera->deleteLater();
    }
    // 释放线程
    if(m_zbar_thread) {
        m_zbar_thread->exit();
        delete m_zbar_thread;
    }
    if(m_opencv_cam_thread) {
        m_opencv_cam_thread->exit();
        delete m_opencv_cam_thread;
    }
    delete ui;
}

// 相机初始化
void MyCamera::CameraInit(){
    if(m_zbar_thread) return;
    // zbar初始化
    m_zbar_thread = new ZbarRenderThread;
    // QCamera获取不到相机，用OpenCV的方式获取
    if(!QCameraInit()){
        ui->finder->hide();
        ui->label->show();
        if(!OpenCVCameraInit()){
            Toast::instance().show(Toast::ERROR, "[QCamera,OpenCV]均找不到可用相机！", this);
        }else{
            Toast::instance().show(Toast::INFO, "[QCamera]找不到可用相机，已使用[OpenCV]方式获取！", this);
        }
        m_opencv_cam_thread = new OpenCVRenderThread();
        connect(m_opencv_cam_thread,SIGNAL(in_update_window_thread(QImage)),this,SLOT(in_update_window(QImage)));
    }else{
        Toast::instance().show(Toast::INFO, "[QCamera]找到可用相机！", this);
    }
    connect(m_zbar_thread,SIGNAL(in_get_barcode_thread(QString)),this,SLOT(in_get_barcode(QString)));
}


void MyCamera::Pause(bool isPause){
    if(m_zbar_thread) m_zbar_thread->pause(isPause);
    if(m_opencv_cam_thread) m_opencv_cam_thread->pause(isPause);
}


// QCameraInit相机初始化
bool MyCamera::QCameraInit(){
    // 获取可用相机集合
    if(!cameras.empty()) cameras.clear();
    ui->comboBox->clear();
    cameras = QMediaDevices::videoInputs();
    for (int i=0; i<cameras.size(); i++) {
        // qDebug() << cameraDevice.description();
        ui->comboBox->addItem(u8"相机["+QString::number(i+1)+u8"]-QCamera-"+cameras.at(i).description());
    }
    if(!cameras.empty()){
        // 方式①
        // 创建接收器，不显示到控件只接收相机视频流进行处理
        //m_captureSession.setVideoSink(&m_videoSink);
        //connect(&m_videoSink, &QVideoSink::videoFrameChanged, this, &MyCamera::in_video_frame);

        // 方式②,显示到控件并接收相机视频流进行处理
        m_captureSession.setVideoOutput(ui->finder);
        connect(m_captureSession.videoSink(), &QVideoSink::videoFrameChanged, this, &MyCamera::in_video_frame);
    }
    return !cameras.empty();
}

// OpenCVCameraInit相机初始化
bool MyCamera::OpenCVCameraInit()
{
    // 获取可用相机集合
    ui->comboBox->clear();

    // 固定10个相机，不管它可不可用
    // for (int i = 0; i < 10; ++i) {
    //     ui->comboBox->addItem(u8"相机["+QString::number(i+1)+u8"]-OpenCV-null");
    // }

    // 获取可用相机
    cv::VideoCapture capture;
    for (int i = 0; i < 10; ++i) {
        if(capture.open(i)){
            capture.release();
            ui->comboBox->addItem(u8"相机["+QString::number(ui->comboBox->count()+1)+u8"]-OpenCV-NULL");
        }
    }
    return ui->comboBox->count();
}

// 开启相机
void MyCamera::startCamera(){
    // QCamera
    if(m_camera){
        m_camera->start();
    }
    // 继续opencv线程
    else if(m_opencv_cam_thread) {
        m_opencv_cam_thread->open(camera_id);
        m_opencv_cam_thread->pause(0);
    }else
        return;

    // 继续QZbar线程
    QImage image;
    m_zbar_thread->pushImage(image);
    m_zbar_thread->pause(0);
}

// 关闭相机
void MyCamera::stopCamera()
{
    // 暂停QZbar线程和opencv线程
    if(m_zbar_thread)  m_zbar_thread->pause();
    if(m_opencv_cam_thread) m_opencv_cam_thread->pause();

    // 暂停QCamera
    if(m_camera)  m_camera->stop();
}

void MyCamera::in_video_frame(const QVideoFrame &frame)
{
    if(frame.isValid()){
        QImage image = frame.toImage();
        m_zbar_thread->pushImage(image);
    }
}

void MyCamera::on_comboBox_currentIndexChanged(int index)
{
    // QCamera
    if(!cameras.empty()){
        if(m_camera){
            m_camera->stop();
            m_camera->deleteLater();
            m_camera = nullptr;
        }
        m_camera = new QCamera(cameras.at(index));
        m_captureSession.setCamera(m_camera);
        if(camera_id!=-1)
            m_camera->start();
    }
    if(camera_id!=-1){
        if(m_opencv_cam_thread) m_opencv_cam_thread->open(index);
    }
    camera_id = index;
}

void MyCamera::in_get_barcode(QString str){
    emit in_return_text(str);
}

void MyCamera::in_update_window(QImage image){
    m_zbar_thread->pushImage(image);
    this->update();
}

// // void MyCamera::paintEvent(QPaintEvent *event)
// // {
// //     QPainter painter(this);
// //     QImage image=m_zbar_thread->getImage();
// //     QString text=(nullptr==m_opencv_cam_thread)?u8"(QCamera)":u8"(OpenCV)";
// //     text = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")+"."+text+"-"+QString::number(image.width())+"x"+QString::number(image.height());
// //     painter.setPen(QPen(Qt::darkCyan));
// //     painter.drawText(5, 20, text);
// //     if(nullptr==m_opencv_cam_thread) return;
// //     if(image.isNull()) return;
// //     // 获取当前窗口的大小
// //     QSize size = ui->label->size();
// //     // 根据窗口大小缩放图像
// //     QImage scaledImage = image.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
// //     // 绘制缩放后的图像
// //     painter.drawImage(QPoint((size.width() - scaledImage.width()) / 2,
// //                              (size.height() - scaledImage.height()) / 2),
// //                       scaledImage);
// // }
